import Koa from "koa";
import router from "./router";
import koaJson from "koa-json";
import cors from "kcors";
import KBody from "koa-body";
import path from "path";
import kStatic from "koa-static";
import {
  checkDirExist,
  getUploadDirName,
  getUploadFileExt,
  getUploadFileName,
} from "./util/upload";
import { SERVICE } from "./config/api.config";

const app = new Koa();
app.use(
  KBody({
    multipart: true, // 支持文件格式
    formidable: {
      // 上传目录
      uploadDir: path.join(__dirname, "./static"),
      // 保留文件扩展名
      keepExtensions: true,
      // 限制10M
      maxFileSize: 1000 * 1024 * 1024,
      onFileBegin: (name, file) => {
        const ext = getUploadFileExt(file.name);
        const dir = path.join(__dirname, `./static/contentFile/${getUploadDirName()}`);
        // 检查文件夹是否存在如果不存在则新建文件夹
        checkDirExist(dir);
        // 重新覆盖 file.path 属性
        file.path = `${dir}/${getUploadFileName(
          ext
        )}`;
      },
    },
  })
);

// 处理跨域
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*")
  await next()
})
app.use(kStatic(path.join(__dirname, "static")));

app.use(koaJson());
app.use(cors());

app.use(router.routes());

app.listen(SERVICE.PORT);
